<template>
  <div class="init_main">
    <div>
      <el-date-picker
        v-model="query.month"
        type="month"
        value-format="yyyy-MM"
        format="yyyy 年 MM 月"
        placeholder=""
        @change="get_info"
      >
      </el-date-picker>
    </div>
    <div class="plato-chart-container">
      <h3 class="chart-title">整改问题柏拉图</h3>
      <div ref="chart" class="chart-container"></div>
    </div>
  </div>
</template>

<script>
import echarts from "echarts";

export default {
  name: "PlatoChart",
  data() {
    return {
      chartInstance: null,
      // 从数据示例中提取的数据
      dataList: [],
      // 需要突出显示的repercent数据
      targetData: {},
      // 标签最大长度
      maxLabelLength: 10,
      query: { month: "" },
    };
  },
  mounted() {},
  beforeDestroy() {
    if (this.chartInstance) {
      this.chartInstance.dispose();
      this.chartInstance = null;
    }
    window.removeEventListener("resize", this.resizeChart);
  },
  methods: {
    get_info() {
      this.$get("/Task/ParetoChart/" + this.query.month).then((res) => {
        if (res.StatusCode != 200) {
          this.$notify.error({
            title: "错误",
            message: res.Errors,
          });
          return;
        }
        if (res.Data.length == 0) {
          this.dataList = [];
          this.targetData = [];
          this.initChart();
          window.addEventListener("resize", this.resizeChart);
          return;
        } else {
          this.dataList = res.Data.relist;
          this.targetData = res.Data.repercent;
          this.initChart();
          window.addEventListener("resize", this.resizeChart);
        }
      });
    },
    initChart() {
      const chartDom = this.$refs.chart;
      this.chartInstance = echarts.init(chartDom);

      // 处理X轴标签，过长则截断并添加省略号
      const formatLabel = (text) => {
        if (text.length > this.maxLabelLength) {
          return text.substring(0, this.maxLabelLength) + "...";
        }
        return text;
      };

      // 准备图表数据
      const categories = this.dataList.map((item) => formatLabel(item.Name));
      const values = this.dataList.map((item) => item.Count);
      const percentages = this.dataList.map((item) => item.PercentAdd);

      // 为柱状图设置颜色，目标数据为红色，其他为蓝色
      const barColors = this.dataList.map((item) =>
        item.Name === this.targetData.Name ? "#ff4d4f" : "#3a7bd5"
      );

      // 为折线图创建样式数组，目标数据为红色，其他为橙色
      const lineColors = this.dataList.map((item) =>
        item.Name === this.targetData.Name ? "#ff4d4f" : "#ff9800"
      );

      const option = {
        title: {
          text: "整改问题柏拉图",
          subtext: "数量与累计百分比",
          left: "center",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross", // 改为十字线辅助，更清晰显示数据点
            crossStyle: {
              color: "#999",
            },
          },
        },
        legend: {
          data: ["数量", "累计百分比(%)"],
          bottom: 10,
          left: "center",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "15%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: categories,
          axisLabel: {
            interval: 0,
            rotate: 45,
            fontSize: 10,
            overflow: "truncate",
            ellipsis: "...",
            width: 80,
          },
        },
        yAxis: [
          {
            type: "value",
            name: "数量",
            min: 0,
            max: Math.max(...values) * 1.2,
            interval: Math.ceil(Math.max(...values) / 5),
          },
          {
            type: "value",
            name: "累计百分比(%)",
            min: 0,
            max: 100,
            interval: 20,
            axisLabel: {
              formatter: "{value}%",
            },
          },
        ],
        series: [
          {
            name: "数量",
            type: "bar",
            data: values,
            itemStyle: {
              color: barColors,
            },
            barWidth: "60%",
          },
          {
            name: "累计百分比(%)",
            type: "line",
            yAxisIndex: 1,
            data: percentages,
            label: {
              show: true,
              position: "top",
            },
            symbol: "circle",
            symbolSize: 8,
            color: "#ff9800", // 默认颜色
            itemStyle: {
              normal: {
                color: (params) => lineColors[params.dataIndex], // 根据索引设置颜色
              },
            },
            lineStyle: {
              normal: {
                width: 2,
              },
            },
          },
        ],
      };

      this.chartInstance.setOption(option);
    },
    resizeChart() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },
  },
};
</script>

<style scoped lang='scss'>
.init_main {
  background-color: #fff;
  height: calc(100vh - 60px);
  border: 1px solid #333;
  border-radius: 5px;
  margin: 5px;
  padding: 10px;
  font-family: "FangSong";
  color: #000;
}
.plato-chart-container {
  width: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.chart-title {
  text-align: center;
  font-size: 18px;
  margin-bottom: 15px;
  color: #333;
}

.chart-container {
  width: 100%;
  height: 400px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 10px;
  box-sizing: border-box;
}

@media (max-width: 768px) {
  .chart-container {
    height: 350px;
  }
}
</style>